package com.example.friend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.example.core.domain.PageDomain;
import com.example.core.domain.TableDataInfo;
import com.example.core.enums.ResultCode;
import com.example.friend.domain.User;
import com.example.friend.domain.UserExam;
import com.example.friend.domain.vo.UserVO;
import com.example.friend.manger.ExamCacheManager;
import com.example.friend.manger.UserCacheManager;
import com.example.friend.mapper.UserExamMapper;
import com.example.friend.service.IUserExamService;
import com.example.scurity.exception.ServiceException;
import com.example.scurity.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private UserCacheManager userCacheManager;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public TableDataInfo list(PageDomain page) {
        //分页参数
        int start = (page.getPageNum() - 1) * page.getPageSize();
        int end = start + page.getPageSize();
        return examCacheManager.selectUserExamList(SecurityUtils.getUserId(), start, end);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int enterExam(Long examId) {
        Long userId = SecurityUtils.getUserId();
//        User user = userCacheManager.getUserById(userId);
//        if(user.getStatus()==0 ||user == null){
//            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
//        }
        UserExam userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        //报名数据存入缓存
        long addCache = examCacheManager.addUserExamCache(userId, examId);
        if (addCache <= 0) {
            return (int) addCache;
        }
        //报名数据存入数据库
        return userExamMapper.insert(userExam);
    }

    @Override
    public boolean hasEnter(Long examId) {
        Long userId = SecurityUtils.getUserId();
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        return !CollectionUtils.isEmpty(userExamList);
    }


}
